#coding = 'utf-8'

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import UI_untitled
import rospy  
import subprocess
from px4 import PX4
import multiprocessing


class DroneManager:
    def __init__(self, layout):
        self.layout = layout  # 传递布局
        self.status_labels = []  # 用于存储状态行
        self.processes = []

    def get_drone_node_count(self):
        """获取当前连接的无人机数量"""
        try:
            output = subprocess.check_output(['rosnode', 'list'], text=True)
            nodes = output.splitlines()
            drone_nodes = [node for node in nodes if "/uav" in node]
            return len(drone_nodes)
        except Exception as e:
            print(f"Error occurred while getting drone nodes: {e}")
            return 0

    def initialize_status_labels(self):
        """根据无人机数量动态生成状态行"""
        drone_count = self.get_drone_node_count()
        print(f"Number of drone nodes: {drone_count}")
        # 为每个无人机生成状态行
        # for i in range(drone_count):
        #     label = QtWidgets.QLabel(f"Drone {i}: Waiting for status...", MainWindow)
        #     label.setStyleSheet("QLabel { background-color : lightgray; color : black; }")
        #     self.status_labels.append(label)
        #     self.layout.addWidget(label)
        # 创建 PX4 对象，并将垂直布局传递给它
        for i in range(2):  # 假设有 6 个无人机
            process = multiprocessing.Process(target=PX4, args=(str(i), self.layout))
            process.start()

            self.processes.append(process)

    def add_button(self, text):
        button = QtWidgets.QPushButton(text)
        self.scroll_area_layout.addWidget(button)

# 按钮点击回调函数
def buttonClicked(girl, drone_manager):
    drone_manager.initialize_status_labels()  # 初始化状态行
    girl.textBrowser.append(f"Number of drone nodes: {drone_manager.get_drone_node_count()}")



if __name__ == '__main__':


    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = UI_untitled.Ui_MainWindow()
    ui.setupUi(MainWindow)

    # 创建 DroneManager 实例，并传递 verticalLayout
    # drone_manager = DroneManager(ui.scrollAreaWidgetContents)
    pLayout = QtWidgets.QGridLayout()
    
    # 动态添加按钮
    for i in range(100):
        pBtn = QtWidgets.QPushButton()
        pBtn.setText(f"按钮{i}")
        pBtn.setMinimumSize(QtCore.QSize(60, 30))  # 设置按钮的最小宽度和高度
        pLayout.addWidget(pBtn)  # 把按钮添加到布局中
        pLayout.addWidget(pBtn, 0, i)  # 将按钮放置在第0行，第i列
    # 将布局放置到 QScrollArea 的内部 QWidget 中
    ui.scrollAreaWidgetContents.setLayout(pLayout)

    # 连接按钮点击事件
    # ui.pushButton.clicked.connect(lambda: buttonClicked(ui, drone_manager))
    MainWindow.show()
    # rospy.init_node("multi_drone_system")
    # uav1 = PX4(uav_id="0")
    # drone_process = multiprocessing.Process(target=drone_run)
    # drone_process.start()
    # 等待所有进程结束
    # 添加按钮到滚动区域
    # pushButton_3 = QtWidgets.QPushButton(ui.scrollAreaWidgetContents)
    # pushButton_3.setGeometry(QtCore.QRect(250, 70, 80, 23))
    # pushButton_3.setObjectName("test")
    
    # ui.scrollArea.addScrollBarWidget(button)

    sys.exit(app.exec_())
    for process in drone_manager.processes:
        process.join()